package components
{	
	import caurina.transitions.Tweener;
	
	import classes.ReturnedImage;
	
	import flash.events.MouseEvent;
	import flash.filters.GlowFilter;
	import flash.geom.Point;
	
	import mx.collections.ArrayCollection;
	import mx.containers.Canvas;
	import mx.controls.Image;
	import mx.core.DragSource;
	import mx.managers.DragManager;
	import mx.managers.PopUpManager;

	public class ImagesList extends Canvas{
		private var pp:ImagePopup = new ImagePopup();
		private var _numberOfImages:int = 7;
		private var _selectedIndex:int = 0;
		private var _maxThumbDimension:Number = 400;
		private var _shrinkCoeff:Number = 0.7;
		private var _sumF:Number=0;
		
		[ArrayElementType("ReturnedImage")]
		private var _dataProvider:ArrayCollection;
		private var dataProviderModified:Boolean = false;
		
		private var thumbChildrenList:ArrayCollection = new ArrayCollection();
		private var zoomChildrenList:ArrayCollection = new ArrayCollection();
		
		public function set numberOfImages(value:int):void{
			if(value!=_numberOfImages){
				_numberOfImages = value;
				invalidateProperties();
				invalidateDisplayList();
			}
		}
		
		public function set selectedIndex(value:int):void{
			if(value!=_selectedIndex){
				if(_selectedIndex<thumbChildrenList.length){
					this.thumbChildrenList.getItemAt(_selectedIndex).filters = [];
				}
				_selectedIndex = value;
				invalidateProperties();
				invalidateDisplayList();
			}
		}
		
		public function set shrinkCoeff(value:Number):void{
			if(value!=_shrinkCoeff){
				_shrinkCoeff = value;
				invalidateProperties();
				invalidateDisplayList();
			}
		}
		
		public function get dataProvider():ArrayCollection{
			return _dataProvider;
		}
		
		public function set dataProvider(value:ArrayCollection):void{
			_dataProvider = value;
			thumbChildrenList = new ArrayCollection();
			zoomChildrenList = new ArrayCollection();
			selectedIndex=0;
			dataProviderModified = true;
			invalidateProperties();
			invalidateSize();
			invalidateDisplayList();
		}
		
		
		public function ImagesList(){
			super();
			this.verticalScrollPolicy = "off";
			this.horizontalScrollPolicy = "off";
			this.setStyle("backgroundColor", 0xFFFFFF);
			this.setStyle("backgroundAlpha", 0);
			this.clipContent = false;
			this._dataProvider = new ArrayCollection();
		}
		
		private function handleMouseMove(event:MouseEvent):void{
			var dragInitiator:MyImage = event.currentTarget as MyImage;
			dragInitiator.hasBeenDragged = true;
			var dragSource:DragSource = new DragSource();
			var proxyImg:Image = new Image;
			proxyImg.source = dragInitiator.img.thumbURL
			proxyImg.width = dragInitiator.width;
			proxyImg.height = dragInitiator.height;
			proxyImg.scaleContent = true;
		//	trace(index);
		//	trace("filename: "  + dataProvider.getItemAt(index).title, "thumbUrl: " + dataProvider.getItemAt(index).thumbUrl, "link: " + dataProvider.getItemAt(index).url);
			dragSource.addData(dragInitiator.img, "draggedImg");
			DragManager.doDrag(dragInitiator, dragSource, event, proxyImg);
		}
		
		private function handleMouseDown(event:MouseEvent):void{
			var dragInitiator:MyImage = event.currentTarget as MyImage;
			dragInitiator.draggingPoint = this.globalToContent(new Point(event.stageX, event.stageY));
		//	trace("dragPoint: " + this.globalToContent(new Point(event.stageX, event.stageY)));
		//	trace("dragInitX: " + dragInitiator.x, "dragInitY: " + dragInitiator.y);
			dragInitiator.draggingPoint.x -= dragInitiator.x;
			dragInitiator.draggingPoint.y -= dragInitiator.y;
		//	trace("dragInitPosX:" + dragInitiator.draggingPoint.x, "dragInitPosY:" + dragInitiator.draggingPoint.y);
		}
		
		private function showPopUp(event:MouseEvent):void{
			pp.image = event.currentTarget.img;
			PopUpManager.addPopUp(pp, this.parent, false);
		}	
		
		private function thumbListClickHandler(event:MouseEvent):void{
			selectedIndex = _dataProvider.getItemIndex(event.currentTarget.img as ReturnedImage);
		}
		
		override protected function createChildren():void{
			super.createChildren();
		//	trace("createChildren()");
		//	Chiamato solo all'aggiunta del componente
		}
		
		override protected function commitProperties():void{
			super.commitProperties();
		
			//	Elimino tutti i vecchi children
			if(dataProviderModified){
				this.removeAllChildren();
				//THUMB LIST PULITO
				for each(var img:ReturnedImage in _dataProvider){
					var tmpImg:MyImage = new MyImage;
					tmpImg.img = img;
					tmpImg.alpha=0;
					tmpImg.addEventListener(MouseEvent.CLICK, thumbListClickHandler);
					tmpImg.addEventListener(MouseEvent.MOUSE_OVER, thumbListClickHandler);
					tmpImg.addEventListener(MouseEvent.MOUSE_MOVE, handleMouseMove);
					tmpImg.addEventListener(MouseEvent.MOUSE_DOWN, handleMouseDown);
					thumbChildrenList.addItem(tmpImg);
					this.addChild(tmpImg);
					dataProviderModified=false;
				}
			}
			if(_selectedIndex<thumbChildrenList.length){
				var greenGlow:GlowFilter = new GlowFilter(0x00FF00);
				this.thumbChildrenList.getItemAt(_selectedIndex).filters = [greenGlow];
			}
			//CREAZIONE VET APPOGGIO
			trace("DATAPROVIDER:");		
			for each(var img:ReturnedImage in _dataProvider){
				trace("i: " + _dataProvider.getItemIndex(img), "name: " + img.title);
			}
			
			trace("ZOOMCHILDRENLIST:");
			for each(var myImg:MyImage in zoomChildrenList){
				trace("i: " + zoomChildrenList.getItemIndex(myImg), "name: " + myImg.img.title);
			}

			var vetApp:ArrayCollection = new ArrayCollection();
			for(var i:int=0;i<_numberOfImages;i++){
				if((_selectedIndex + i - (_numberOfImages-1)/2) >= 0 && (_selectedIndex + i - (_numberOfImages-1)/2)<_dataProvider.length){
					vetApp.addItem(dataProvider.getItemAt(_selectedIndex + i - (_numberOfImages-1)/2) as ReturnedImage);
					trace("AGGIUNTA IMG A VETAPP! i:" + String(_selectedIndex + i - (_numberOfImages-1)/2), "name: " + dataProvider.getItemAt(_selectedIndex + i - (_numberOfImages-1)/2).title);
				}
			}
			
			for(var i:int=0; i<zoomChildrenList.length; i++){
				if(!vetApp.contains(zoomChildrenList.getItemAt(i).img)){
					this.removeChild(zoomChildrenList.getItemAt(i) as MyImage);
					zoomChildrenList.removeItemAt(i);
					i--;
					trace("RIMOSSA IMG DA ZOOMLIST")
				}
			}
			
			//AGGIUNGERE A ZOOMLIST QUELLI CHE NON CI SONO GIA'
			for(var i:int=0; i<vetApp.length; i++){
				var found:Boolean = false
				for each(var daImg:MyImage in zoomChildrenList){
					if(daImg.img == vetApp.getItemAt(i)){
						found=true;
						trace("TROVATA IMG GIA PRESENTE")
					}
				}
				if(!found){
					var tmpZoomImg:MyImage = new MyImage;
					tmpZoomImg.alpha=0;
					tmpZoomImg.x = _dataProvider.getItemIndex(vetApp.getItemAt(i))*(unscaledWidth/dataProvider.length);
					tmpZoomImg.img = vetApp.getItemAt(i) as ReturnedImage;
					tmpZoomImg.addEventListener(MouseEvent.CLICK, showPopUp);
					tmpZoomImg.addEventListener(MouseEvent.MOUSE_MOVE, handleMouseMove);
					tmpZoomImg.addEventListener(MouseEvent.MOUSE_DOWN, handleMouseDown);
					zoomChildrenList.addItemAt(tmpZoomImg, i);
					this.addChildAt(tmpZoomImg,0);
					trace("AGGIUNTA IMG CHE NON ESITEVA PRIMA");
				}
			}
			
			_sumF = 0;
			for(var k:int=-(_numberOfImages-1)/2; k<=(_numberOfImages-1)/2; k++){
				trace("sumf prima della somma: " + _sumF);  
				_sumF += Math.pow(_shrinkCoeff,Math.abs(k));
				trace("sumf dopo la somma: " + _sumF);  
			}
			trace("sumf totale:" + _sumF);
			
			trace("--------");
		}

		override protected function measure():void{
			super.measure();
		//	trace("Measure");
			
		//	measuredMinWidth = 0;
		//	measuredMinHeight = 0;
		}
		
		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void{
			super.updateDisplayList(unscaledWidth, unscaledHeight);
		//	trace("updatedisplay");
			//POSIZIONAMENTO THUMB!
			
			var thumbDimension:Number = (unscaledWidth/thumbChildrenList.length)<_maxThumbDimension?(unscaledWidth/thumbChildrenList.length):_maxThumbDimension;
			thumbDimension = thumbDimension<unscaledHeight*0.25?thumbDimension:unscaledHeight*0.25;
			for(var i:int=0; i<thumbChildrenList.length; i++){
				var thumbMyImg:MyImage = this.getChildAt(this.getChildren().indexOf(thumbChildrenList.getItemAt(i))) as MyImage;
				Tweener.addTween(thumbMyImg,{width:thumbDimension, height:thumbDimension, x:i*thumbDimension, y:0, alpha:1, time:1});
			}
			
			//POSIZIONAMENTO ZOOM!
			
			var sxOffset:int = (_selectedIndex-(_numberOfImages-1)/2)<0?(_numberOfImages-1)/2-_selectedIndex:0;
		//	var dxOffset:int = (_selectedIndex+(_numberOfImages-1)/2)>(_dataProvider.length-1)?(_selectedIndex+(_numberOfImages-1)/2)-(_dataProvider.length-1):0;
			var nextWidth:Number = 0;
			for(var j:int=-(_numberOfImages-1)/2; j<=(_numberOfImages-1)/2; j++){
				trace("sxOffs: " + sxOffset, "j: " + j);
				var tmpWidth:Number = Math.pow(_shrinkCoeff,Math.abs(j))*unscaledWidth/_sumF;
				trace("tmpWidth: " + tmpWidth);
				if((j+(_numberOfImages-1)/2-sxOffset)>=0 && (j+(_numberOfImages-1)/2-sxOffset)<zoomChildrenList.length){
					var zoomMyImg:MyImage = this.getChildAt(this.getChildren().indexOf(zoomChildrenList.getItemAt(j + (_numberOfImages-1)/2 - sxOffset))) as MyImage;
					var actualDimension:Number = tmpWidth<(_maxThumbDimension<unscaledHeight-thumbDimension?_maxThumbDimension:unscaledHeight-thumbDimension)?tmpWidth:(_maxThumbDimension<unscaledHeight-thumbDimension?_maxThumbDimension:unscaledHeight-thumbDimension);
					Tweener.addTween(zoomMyImg,{width:actualDimension, height:actualDimension, x:nextWidth+(tmpWidth-actualDimension)/2, y:(unscaledHeight + thumbDimension)/2 -actualDimension/2, alpha:1, time:0.3, transition:"linear"});
				}
				nextWidth+=tmpWidth;
				trace("nextWidth: " + nextWidth);
			}
			
		}
	}
}